//
//  SearchViewController.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2016/12/27.
//  Copyright © 2021年 梁慧聪. All rights reserved.
//

#import "CLVCSearch.h"
#import "CLSearchInputView.h"
#import "CLHTTPClient+SearchSug.h"
#import "CLBaiduSugResponseModel.h"
#import "CLSearchTableViewCell.h"
#import "CLHttpHelper.h"
#import "CLKeyboardHelper.h"

#define SEARCH_INPUTVIEW_HEIGHT 76

static NSString * const CELL = @"CELL";

@interface CLVCSearch ()<UITableViewDelegate, UITableViewDataSource, CLKeyboardHelperDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) CLSearchInputView *searchInputView;
@property (nonatomic, strong) NSURLSessionDataTask *bdRecoTask;
@property (nonatomic, copy) NSArray *searchResultArray;
@property (nonatomic, strong) CLKeyboardState *keyboardState;

@end

@implementation CLVCSearch

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"搜索";
    [[CLKeyboardHelper sharedInstance] addDelegate:self];
    
    [self commonUIInit];
}

- (void)commonUIInit{
    if (@available(iOS 13.0, *)) {
        UIColor *backgroundColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            return [traitCollection userInterfaceStyle] == UIUserInterfaceStyleDark ? UIColorFromRGB(0x3C3C3C) : CL_MAIN_BACKGROUNDCOLOR;
        }];
        self.view.backgroundColor = backgroundColor;
    }
    self.searchInputView = ({
        CLSearchInputView *inputView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([CLSearchInputView class]) owner:nil options:nil] objectAtIndex:0];

        inputView.frame = CGRectMake(self.view.bounds.origin.x, self.view.height - SEARCH_INPUTVIEW_HEIGHT, self.view.width, SEARCH_INPUTVIEW_HEIGHT);
        [self.view addSubview:inputView];
        
        [Notifier addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
        
        [inputView.textField setText:self.origTextFieldString];
        inputView.slider.enabled = (self.origTextFieldString.length > 0);
        
        inputView;
    });
    
    self.tableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        
        tableView.translatesAutoresizingMaskIntoConstraints = NO;
        
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[tableView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(tableView)]];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[tableView]-0-[_searchInputView]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(tableView,_searchInputView)]];
        
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.f]];
#pragma clang diagnostic pop
        [tableView setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisVertical];
        
        tableView.delegate = self;
        tableView.dataSource = self;
        
        [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CLSearchTableViewCell class]) bundle:nil] forCellReuseIdentifier:CELL];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        tableView;
    });
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.searchInputView.textField becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self changeSearchInputViewPoint:self.keyboardState];
    });
}

- (void)cancelRecoTaskIfNeeded{
    if (self.bdRecoTask && (self.bdRecoTask.state == NSURLSessionTaskStateRunning || self.bdRecoTask.state == NSURLSessionTaskStateSuspended)) {
        [self.bdRecoTask cancel];
    }
}

- (void)textFieldTextDidChange:(NSNotification *)notify{
    UITextField *textField = [notify object];
    if (textField.text.length > 0) {
        self.searchInputView.slider.enabled = YES;
        
        [self cancelRecoTaskIfNeeded];
        
        WEAK_SELF;
        self.bdRecoTask = [[CLHTTPClient sharedInstance] getSugWithKeyword:textField.text success:^(NSURLSessionDataTask *task, CLBaseResponseModel *model){
            STRONG_SELF;
            if (strongSelf) {
                CLBaiduSugResponseModel *bdModel = (CLBaiduSugResponseModel *)model;
                strongSelf.searchResultArray = bdModel.sugArray;
                [strongSelf.tableView reloadData];
            }
        }fail:^(NSURLSessionDataTask *task, CLBaseResponseModel *model){
            ;
        }];
    }
    else{
        self.searchInputView.slider.enabled = NO;
    }
}

#pragma mark - CLKeyboardHelperDelegate

- (void)keyboardHelper:(CLKeyboardHelper *)keyboardHelper keyboardWillShowWithState:(CLKeyboardState *)state{
    [self changeSearchInputViewPoint:state];
}

- (void)keyboardHelper:(CLKeyboardHelper *)keyboardHelper keyboardWillHideWithState:(CLKeyboardState *)state{
    [self changeSearchInputViewPoint:state];
}

- (void)changeSearchInputViewPoint:(CLKeyboardState *)state{
    self.keyboardState = state;
    
    CGFloat keyBoardEndY = self.view.height - [state intersectionHeightForView:self.view];
    
    // 添加移动动画，使视图跟随键盘移动
    [UIView animateWithDuration:state.animationDuration animations:^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:state.animationCurve];
#pragma clang diagnostic pop
        
        self.searchInputView.center = CGPointMake(self.searchInputView.centerX, keyBoardEndY - self.searchInputView.height/2.0f);
    }];
}

#pragma mark - UITableViewDataSource Method

- (CLSearchTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CLSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL];
    
    [cell updateCellWithString:self.searchResultArray[indexPath.row]];
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.searchResultArray.count;
}

#pragma mark - UITableViewDelegate Method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CLSearchTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *text = [cell cellText];
    if (text) {
        [[CLDelegateManager sharedInstance] performSelector:@selector(browserContainerViewLoadWebViewWithSug:) arguments:@[text] key:kDelegateManagerBrowserContainerLoadURL];
    }
    [self.navigationController popToRootViewControllerAnimated:NO];
}

- (void)dealloc{
    [self cancelRecoTaskIfNeeded];
    [Notifier removeObserver:self];
    
}

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    if (@available(iOS 13.0, *)) {
        UIColor *backgroundColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            return [traitCollection userInterfaceStyle] == UIUserInterfaceStyleDark ? UIColorFromRGB(0x3C3C3C) : CL_MAIN_BACKGROUNDCOLOR;
        }];
        self.view.backgroundColor = backgroundColor;
    }
}
@end
